<template>
  <div class="boss-smart-recruitment-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">Boss智能招聘助手</h1>
          <div class="status-indicator">
            <span class="status-dot" :class="serverStatus === 'online' ? 'online' : 'offline'"></span>
            <span class="status-text">{{ serverStatus === 'online' ? '在线' : '离线' }}</span>
          </div>
        </div>
        <div class="header-actions">
          <button class="action-btn" @click="showTools = !showTools">
            <i class="tools-icon">🔧</i>
            工具
          </button>
          <button class="action-btn" @click="clearChat">
            <i class="clear-icon">🗑️</i>
            清空
          </button>
          <button class="action-btn" @click="checkServerStatus">
            <i class="status-icon">🔄</i>
            检查状态
          </button>
        </div>
      </div>
    </div>

    <!-- 工具面板 -->
    <div v-if="showTools" class="tools-panel">
      <div class="tools-header">
        <h3>可用工具 ({{ availableTools.length }})</h3>
        <button class="close-btn" @click="showTools = false">×</button>
      </div>
      <div class="tools-grid">
        <div 
          v-for="tool in availableTools" 
          :key="tool.name"
          class="tool-card"
          @click="selectTool(tool)"
        >
          <div class="tool-icon">
            <i class="gear-icon">⚙️</i>
          </div>
          <div class="tool-content">
            <h4 class="tool-name">{{ tool.name }}</h4>
            <p class="tool-description">{{ tool.description }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 欢迎区域 -->
      <div v-if="!hasMessages" class="welcome-section">
        <div class="welcome-content">
          <div class="welcome-icon">👋</div>
          <h2 class="welcome-title">欢迎使用Boss智能招聘助手</h2>
          <p class="welcome-subtitle">我可以帮助您进行招聘相关的工作，请选择或输入您的问题</p>
          
          <!-- 快捷操作按钮 -->
          <div class="quick-actions">
            <button 
              v-for="action in quickActions" 
              :key="action.id"
              class="quick-action-btn"
              @click="handleQuickAction(action)"
            >
              {{ action.text }}
            </button>
          </div>
        </div>
      </div>

      <!-- 聊天区域 -->
      <div v-if="hasMessages" class="chat-section">
        <div class="chat-messages" ref="messagesContainer">
          <div 
            v-for="(message, index) in messages" 
            :key="index"
            class="message-item"
            :class="{ 'user-message': message.type === 'user', 'assistant-message': message.type === 'assistant' }"
          >
            <div class="message-avatar">
              <div v-if="message.type === 'user'" class="user-avatar">👤</div>
              <div v-else class="assistant-avatar">🤖</div>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="renderMessage(message.content)"></div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
          
          <!-- 加载指示器 -->
          <div v-if="isLoading" class="message-item assistant-message typing">
            <div class="message-avatar">
              <div class="assistant-avatar">🤖</div>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-section">
        <div class="input-container">
          <textarea
            v-model="inputMessage"
            ref="messageInput"
            placeholder="输入您的问题..."
            class="message-input"
            rows="1"
            @keydown.enter.prevent="handleEnter"
            @input="adjustTextareaHeight"
            :disabled="isLoading"
          ></textarea>
          <button
            class="send-btn"
            :disabled="!inputMessage.trim() || isLoading"
            @click="sendMessage()"
          >
            <i class="send-icon">📤</i>
            发送 →
          </button>
        </div>
        <div class="input-hint">
          提示：您可以问我关于招聘的任何问题。按Enter 发送，Shift + Enter 换行
        </div>
      </div>
    </div>

    <!-- 侧边栏头像 -->
    <div class="sidebar-avatars">
      <div class="avatar-item">
        <div class="avatar-circle">DO</div>
      </div>
      <div class="avatar-item">
        <div class="avatar-circle">CA</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { agentBossApi } from './frontend_api.js'  // 使用适配的API文件

const router = useRouter()

// 响应式数据
const showTools = ref(false)
const inputMessage = ref('')
const isLoading = ref(false)
const messages = ref([])
const messageInput = ref(null)
const messagesContainer = ref(null)
const serverStatus = ref('offline')

// 可用工具列表 - 基于后端实际工具
const availableTools = ref([
  {
    name: 'ResumeGenerateOrAnalyze',
    description: '解析/生成/优化简历：输入为json或文本，输出结构化或docx路径'
  },
  {
    name: 'JobSearch',
    description: '职位检索：传入关键词(岗位/标签/城市关键字)，直接返回前10条职位明细(JSON)'
  },
  {
    name: 'KnowledgeSearch',
    description: '知识检索：对问题进行混合检索并返回结果数量'
  }
])

// 快捷操作
const quickActions = ref([
  { id: 1, text: '帮我查询Python工程师职位' },
  { id: 2, text: '帮我生成一份简历' },
  { id: 3, text: '搜索Java开发相关职位' },
  { id: 4, text: '查询前端工程师职位' }
])

// 计算属性
const hasMessages = computed(() => messages.value.length > 0)

// 方法
const selectTool = (tool) => {
  inputMessage.value = `使用${tool.name}工具: ${tool.description}`
  showTools.value = false
  messageInput.value?.focus()
}

// 安全的消息发送包装函数
const safeSendMessage = async (messageText) => {
  // 确保传入的是字符串
  if (typeof messageText === 'string') {
    await sendMessage(messageText)
  } else {
    console.error('safeSendMessage: 传入的不是字符串:', messageText)
  }
}

const handleQuickAction = async (action) => {
  // 确保传递的是文本内容，而不是事件对象
  console.log('快捷操作点击:', {
    action: action,
    actionType: typeof action,
    actionText: action?.text
  })
  
  // 检查是否是事件对象
  if (action && typeof action === 'object' && action.isTrusted) {
    console.error('检测到事件对象，无法处理')
    return
  }
  
  const messageText = action?.text || action
  if (!messageText || typeof messageText !== 'string') {
    console.error('无效的消息文本:', messageText)
    return
  }
  
  await safeSendMessage(messageText)
}

const handleEnter = (event) => {
  if (event.shiftKey) {
    // Shift + Enter 换行
    return
  }
  // Enter 发送
  event.preventDefault()
  sendMessage()
}

const adjustTextareaHeight = () => {
  const textarea = messageInput.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
  }
}

const sendMessage = async (text = null) => {
  // 调试：记录所有传入的参数
  console.log('sendMessage 被调用:', {
    text: text,
    textType: typeof text,
    textIsEvent: text && typeof text === 'object' && text.isTrusted,
    inputValue: inputMessage.value
  })
  
  // 如果传入的是事件对象，直接忽略
  if (text && typeof text === 'object' && text.isTrusted) {
    console.error('sendMessage: 检测到事件对象，直接忽略:', text)
    return
  }
  
  // 确保message是字符串类型
  let message = text || inputMessage.value.trim()
  
  // 强化的事件对象检测
  if (typeof message === 'object' && message !== null) {
    // 检查是否是事件对象
    if (message.isTrusted || message.type || message.target || message.preventDefault) {
      console.error('检测到事件对象，忽略:', message)
      return // 直接返回，不处理事件对象
    }
    
    // 尝试提取text属性
    if (message.text) {
      message = message.text
    } else if (message.target && message.target.value) {
      message = message.target.value
    } else if (message.content) {
      message = message.content
    } else {
      console.warn('无法从对象中提取消息内容:', message)
      return // 无法提取内容，直接返回
    }
  }
  
  // 确保最终是字符串并去除空白
  message = String(message || '').trim()
  
  // 调试信息
  console.log('发送消息:', {
    originalText: text,
    inputValue: inputMessage.value,
    finalMessage: message,
    messageLength: message.length
  })
  
  if (!message || isLoading.value) {
    console.warn('消息为空或正在加载中，取消发送')
    return
  }

  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: String(message),
    timestamp: new Date()
  })

  // 清空输入框
  inputMessage.value = ''
  adjustTextareaHeight()

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  // 发送到后端
  isLoading.value = true
  try {
    const response = await agentBossApi.sendMessage(message)
    
    // 修复：正确处理后端响应格式
    let assistantContent = ''
    if (response.success && response.content) {
      assistantContent = response.content
    } else if (response.content) {
      assistantContent = response.content
    } else if (response.message) {
      assistantContent = response.message
    } else if (response.response) {
      assistantContent = response.response
    } else if (response.data && response.data.response) {
      assistantContent = response.data.response
    } else {
      assistantContent = '收到回复'
    }
    
    // 添加助手回复
    messages.value.push({
      type: 'assistant',
      content: String(assistantContent),
      timestamp: new Date()
    })
  } catch (error) {
    console.error('发送消息失败:', error)
    messages.value.push({
      type: 'assistant',
      content: `抱歉，我遇到了一些问题：${error.message}。请检查后端服务是否运行正常。`,
      timestamp: new Date()
    })
  } finally {
    isLoading.value = false
    await nextTick()
    scrollToBottom()
  }
}

const clearChat = () => {
  messages.value = []
  inputMessage.value = ''
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const renderMessage = (content) => {
  // 确保content是字符串类型
  if (typeof content !== 'string') {
    console.warn('renderMessage received non-string content:', content)
    content = String(content || '')
  }
  
  // 简单的markdown渲染
  return content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>')
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const checkServerStatus = async () => {
  try {
    const status = await agentBossApi.getSystemStatus()
    serverStatus.value = status.status === 'running' ? 'online' : 'offline'
    console.log('服务器状态:', status)
  } catch (error) {
    serverStatus.value = 'offline'
    console.error('检查服务器状态失败:', error)
  }
}

// 生命周期
onMounted(async () => {
  // 检查服务器状态
  await checkServerStatus()
  
  // 验证token
  agentBossApi.validateToken()
})

onUnmounted(() => {
  // 清理
})
</script>

<style scoped>
.boss-smart-recruitment-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 1rem 2rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-dot.online {
  background: #4ade80;
}

.status-dot.offline {
  background: #ef4444;
}

.status-text {
  font-size: 0.875rem;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: background 0.2s;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 工具面板 */
.tools-panel {
  background: white;
  margin: 1rem 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tools-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
}

.tools-header h3 {
  margin: 0;
  font-size: 1.125rem;
  color: #1e293b;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #64748b;
}

.tools-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1rem;
  padding: 1.5rem;
}

.tool-card {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  padding: 1rem;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.tool-card:hover {
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

.tool-icon {
  width: 40px;
  height: 40px;
  background: #f1f5f9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.tool-name {
  font-size: 1rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 0.5rem 0;
}

.tool-description {
  font-size: 0.875rem;
  color: #64748b;
  margin: 0;
  line-height: 1.5;
}

/* 主要内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  width: 100%;
}

/* 欢迎区域 */
.welcome-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.welcome-content {
  max-width: 600px;
}

.welcome-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.welcome-title {
  font-size: 2rem;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 1rem 0;
}

.welcome-subtitle {
  font-size: 1.125rem;
  color: #64748b;
  margin: 0 0 2rem 0;
  line-height: 1.6;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1rem;
}

.quick-action-btn {
  background: white;
  border: 1px solid #e2e8f0;
  color: #1e293b;
  padding: 1rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: all 0.2s;
  text-align: left;
}

.quick-action-btn:hover {
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.1);
}

/* 聊天区域 */
.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 400px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 0;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message-item {
  display: flex;
  gap: 1rem;
  max-width: 80%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.user-avatar, .assistant-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
}

.user-avatar {
  background: #667eea;
  color: white;
}

.assistant-avatar {
  background: #f1f5f9;
  color: #64748b;
}

.message-content {
  flex: 1;
}

.message-text {
  background: white;
  padding: 1rem 1.5rem;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  line-height: 1.6;
  color: #1e293b;
}

.user-message .message-text {
  background: #667eea;
  color: white;
}

.message-time {
  font-size: 0.75rem;
  color: #64748b;
  margin-top: 0.5rem;
  text-align: right;
}

.user-message .message-time {
  text-align: left;
}

/* 加载指示器 */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 1rem 1.5rem;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #667eea;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* 输入区域 */
.input-section {
  margin-top: 2rem;
}

.input-container {
  display: flex;
  gap: 1rem;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 1rem;
  font-size: 1rem;
  resize: none;
  min-height: 50px;
  max-height: 120px;
  font-family: inherit;
}

.message-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.send-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 1rem 2rem;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: background 0.2s;
  white-space: nowrap;
}

.send-btn:hover:not(:disabled) {
  background: #5a67d8;
}

.send-btn:disabled {
  background: #cbd5e1;
  cursor: not-allowed;
}

.input-hint {
  font-size: 0.875rem;
  color: #64748b;
  margin-top: 0.5rem;
  text-align: center;
}

/* 侧边栏头像 */
.sidebar-avatars {
  position: fixed;
  right: 2rem;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.avatar-item {
  cursor: pointer;
}

.avatar-circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #667eea;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 0.875rem;
  transition: transform 0.2s;
}

.avatar-circle:hover {
  transform: scale(1.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    padding: 1rem;
  }
  
  .header-content {
    flex-direction: column;
    gap: 1rem;
  }
  
  .main-content {
    padding: 1rem;
  }
  
  .tools-panel {
    margin: 1rem;
  }
  
  .tools-grid {
    grid-template-columns: 1fr;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
  
  .message-item {
    max-width: 95%;
  }
  
  .sidebar-avatars {
    display: none;
  }
}
</style>
